package org.bdware.repository.webService.controller;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import org.apache.log4j.Logger;
import org.bdware.bdoa.authentication.annotation.AuthRequired;
import org.bdware.bdoa.authentication.utils.JwtContext;
import org.bdware.doip.core.model.digitalObject.DigitalObject;
import org.bdware.doip.core.model.digitalObject.Element;
import org.bdware.doip.core.utils.DoipGson;
import org.bdware.repository.webService.model.RequestWrapper;
import org.bdware.repository.webService.model.ResponseWrapper;
import org.bdware.repository.webService.service.DigitalObjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 数字对象管理模块
 */
@RestController
@RequestMapping("/doa/repo/do")
public class DigitalObjectControllerWithWrapper {
    Logger logger = Logger.getLogger(DigitalObjectControllerWithWrapper.class);

    @Autowired
    private DigitalObjectService doService;

    @RequestMapping("")
    public String index() {
        List<String> indexStr = new ArrayList<>();
        indexStr.add("/getDetailByID");
        indexStr.add("/getByUser");
        indexStr.add("/getAllGroupByUser");
        indexStr.add("/create");
        indexStr.add("/delete");
        indexStr.add("/search");
        return new Gson().toJson(indexStr);
    }

    /*
        url:http://127.0.0.1:8080/do/getdetailbyid
        post,参数doID
        返回JSon格式的数字对象字符串
     */
    @RequestMapping("/getDetailByID")
    public ResponseWrapper getByID(@RequestParam("doID") String doID) {
        logger.debug("DO ID: " + doID);
        DigitalObject digitalObject = doService.getDOByID(doID);

        if(digitalObject == null) return new ResponseWrapper("{}");
        //对于web前端服务，如果element中有文件，不适合直接传递给浏览器，稍作处理
        if(digitalObject.elements != null){
            for(int i = 0; i < digitalObject.elements.size(); i++){
                if("file".equals(digitalObject.elements.get(i).type)){
                    logger.info("==element file==");
                    digitalObject.elements.get(i).dataString = "";
                }
            }
        }

//        logger.debug("DO String: " + digitalObject.toString());
        return new ResponseWrapper(new Gson().toJson(digitalObject));
    }

    /*
        url:http://127.0.0.1:8080/do/getbyuser
        post,参数userID
        返回JSon格式的数字对象字符串
     */
    @RequestMapping("getByUser")
    @AuthRequired(required = true)
    public ResponseWrapper getListByUserID(){
        String userID = (String)JwtContext.get("doi");
        if(userID == null) userID = "anonymous";
        JsonArray doList = doService.getDOListByUserID(userID);
        return new ResponseWrapper(new Gson().toJson(doList));
    }

    /*
        url:c
        get, 无参数
        返回JSon格式的数字对象字符串
     */
    @RequestMapping("getAllGroupByUser")
    public ResponseWrapper getAllGroupByUserID(){
        HashMap<String, JsonArray> doList = doService.getAllDOListGroupByUserID();
        return new ResponseWrapper(new Gson().toJson(doList));
    }

    /*
        url:http://127.0.0.1:8080/do/create
        post, 参数为Json格式的DO字符串，id可为空，参考格式
        {
            "id": "",
            "type": "0.TYPE/DO",
            "attributes": {
                "title": "sam发推：什么时候由媒体来宣布下任总统了？",
                "source": "环球网",
                "publishTime": "2020-11-09 06:46",
                "url": "https://world.huanqiu.com/article/40cnJsElNVt",
                "metadata": {
                    "标题": "柳熠发推：什么时候由媒体来宣布下任总统了？",
                    "来源": "环球网",
                    "分类": "新闻"
                }
            },
            "elements": [{
                "id": "test",
                "length": "3",
                "dataString": "aaa",
                "attributes": {
                    "attr":"bbb"
                }
            }]
        }
        返回去掉ElementData的JSon格式的数字对象字符串，包括新注册的ID
     */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    @AuthRequired(required = true)
    public ResponseWrapper createDigitalObject(@RequestBody  String doString){
        String userID = (String)JwtContext.get("doi");
        logger.info("create do with user: " + userID);
        logger.info(doString);
        if(userID == null) userID = "anonymous";
        DigitalObject digitalObject = DoipGson.getDoipGson().fromJson(doString,DigitalObject.class);
        logger.info(digitalObject.toString());
        if(digitalObject.elements!= null)
            for (Element e:digitalObject.elements) {
                if(e.dataString != null){
                    e.setData(e.dataString.getBytes());
                    e.dataString = null;
                }
            }
        return new ResponseWrapper(doService.storeDO(digitalObject,userID));

    }

    /*
        url:http://127.0.0.1:8080/do/delete
        post,参数doID
        返回JSon格式的数字对象字符串
     */
    @RequestMapping("delete")
    @AuthRequired(required = true)
    public ResponseWrapper deleteDigitalObject(@RequestParam("doID") String doID){
        String userID = (String)JwtContext.get("doi");
        if(userID == null) userID = "anonymous";
        if(doService.deleteDOByID(doID,userID))
            return new ResponseWrapper("success");
        else
            return new ResponseWrapper("failed");
    }

    /*
        url:http://127.0.0.1:8080/do/search
        post,参数query
        返回100条搜索匹配的结果，每条结果包含所有元数据
     */
    @RequestMapping("search")
    public ResponseWrapper search(@RequestParam("query") String query){
        return new ResponseWrapper(doService.search(query,100));
    }
}
